//
// StoreNuke.Net -  http://www.storenuke.net
// Copyright (c) 2005
// by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http://www.willowtreesoftware.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace StoreNuke.StarterKit.Commerce.StoreControls
{

	/// <summary>
	///		Summary description for CheckOut.
	/// </summary>
	public class CheckOut : StoreControl
	{
		protected Label Header;
		protected Label Message;
		protected DataGrid MyDataGrid;
		protected Label TotalLbl;
		protected Label Label1;
		protected Panel pnHide;
		protected Label lblShipTo;
		protected Label lblBillTo;
		protected PlaceHolder phGateway;
		protected __AddressControl _AddressControl1;
		protected __AddressControl _AddressControl2;
		protected DropDownList ddlShipTo;
		protected DropDownList ddlBillTo;
		protected System.Web.UI.WebControls.LinkButton btnAddEditAddress;
		protected System.Web.UI.WebControls.LinkButton btnEdit;
		protected System.Web.UI.WebControls.LinkButton btnNew;
		protected System.Web.UI.WebControls.LinkButton btnSave;
		protected CustomersDB custDetails = new CustomersDB();

		//These are Properties so the data on this contral 
		//can be accessed by the Gateways

		public __AddressControl BillingAddress
		{
			get{return _AddressControl2;}
		}

		public string CartMessage
		{
			get{return Message.Text;}
			set{Message.Text = value;}
		}

		public string ShipToAddress
		{
			get{return ddlShipTo.SelectedValue;}
			set{ddlShipTo.SelectedValue = value;}
		}

		public string BillToAddress
		{
			get{return ddlBillTo.SelectedValue;}
			set{ddlBillTo.SelectedValue = value;}
		}

		public string Total
		{
			get{return TotalLbl.Text.Substring(1);}
		}

		public bool HidePaymentPanel
		{
			set{pnHide.Visible = (!(bool)value);}
		}

		//*******************************************************
		//
		// The Page_Load event on this page is used to load the
		// ShoppingCart DataGrid *the first time* the page is
		// accessed.
		//
		// Note that subsequent postbacks to the page *do not*
		// reload the Datagrid.  Instead, we rely on the control's
		// built-in viewstate management to rebuild the control
		// on the server.
		//
		//*******************************************************

		private void Page_Load(object sender, EventArgs e) 
		{
			if (Page.IsPostBack == false) 
			{
				if(Context.User.Identity.Name != "")
				{
					// Calculate end-user's shopping cart ID
					ShoppingCartDB cart = new ShoppingCartDB();
					String cartId = cart.GetShoppingCartId();

					// Populate datagrid with shopping cart data
					MyDataGrid.DataSource = cart.GetItems(cartId);
					MyDataGrid.DataBind();

					SetAddressInformation();

					// Update total price label
					TotalLbl.Text = String.Format( "{0:c}", cart.GetTotal(cartId));
				}
				else
				{
					Response.Redirect("Default.aspx?scid=6");
				}
			}
		}

		private void SetAddressInformation()
		{
			//get addressess
			ddlShipTo.DataSource = custDetails.GetAllAddresses(Convert.ToInt32(Context.User.Identity.Name));
			ddlShipTo.DataBind();
	
			ddlBillTo.DataSource = custDetails.GetAllAddresses(Convert.ToInt32(Context.User.Identity.Name));
			ddlBillTo.DataBind();
	
			try
			{
				GetBillToAddress(ddlBillTo.SelectedValue);
				GetShipToAddress(ddlShipTo.SelectedValue);
			}
			catch
			{
				//Nothing
			}
		}

		private GatewayControl LoadCart(string CartPath) 
		{ 
			GatewayControl ctlSkin = new GatewayControl(); 
			string error;

			try 
			{ 
				ctlSkin = ((GatewayControl)(LoadControl(CartPath)));
			} 
			catch (Exception ex) 
			{ 
				error = "<center>Could Not Load Skin: " + CartPath + " Error: " + Server.HtmlEncode(ex.Message) + "</center><br>"; 
				//SkinError.Visible = true; 
			} 
			return ctlSkin; 
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			StoreGlobalDB store = new StoreGlobalDB();
			GatewayControl ctlCart = new GatewayControl();
			ctlCart = LoadCart("../Gateways/" + store.GetGatewayPath() + "/gateway.ascx");
			ctlCart.CheckOut = this;
			//ctlCart. = this;
			//Add skin to page
			phGateway.Controls.Add(ctlCart);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnAddEditAddress.Click += new System.EventHandler(this.btnAddEditAddress_Click);
			this.ddlShipTo.SelectedIndexChanged += new System.EventHandler(this.ddlShipTo_SelectedIndexChanged);
			this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
			this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			this.ddlBillTo.SelectedIndexChanged += new System.EventHandler(this.ddlBillTo_SelectedIndexChanged);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void GetBillToAddress(string value)
		{
			BindAddressControl(_AddressControl2,Convert.ToInt32(value));
		}

		private void GetShipToAddress(string value)
		{
			BindAddressControl(_AddressControl1,Convert.ToInt32(value));
		}

		private void BindAddressControl(__AddressControl ac, int id)
		{
			SqlDataReader dr = custDetails.GetSingleAddresses(id);
			if(dr.Read())
			{
				ac.Attn = dr["ATTN"].ToString();
				ac.Address1 = dr["Address1"].ToString();
				ac.Address2 = dr["Address2"].ToString();
				ac.City = dr["City"].ToString();
				ac.Country = dr["CountryCode"].ToString();
				ac.Region = dr["RegionCode"].ToString();
				ac.PostalCode = dr["PostalCode"].ToString();
				ac.Phone1 = dr["Phone1"].ToString();
				ac.Phone2 = dr["Phone2"].ToString();
			}
			dr.Close();
		}

		private void ddlShipTo_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			GetShipToAddress(ddlShipTo.SelectedValue);
		}

		private void ddlBillTo_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			GetBillToAddress(ddlBillTo.SelectedValue);
		}

		private void btnAddEditAddress_Click(object sender, System.EventArgs e)
		{
			if(phGateway.Visible)
			{
				btnAddEditAddress.Text = "Cancel Edit Address";
				SetEditVisibility(true);
			}else
			{
				btnAddEditAddress.Text = "Add or Edit Address";
				SetEditVisibility(false);
				btnSave.Visible = (!ddlShipTo.Enabled);
			}
		}

		private void SetEditVisibility(bool visible)
		{
			btnEdit.Visible = visible;
			btnSave.Visible = (!visible);
			btnNew.Visible = visible;
			phGateway.Visible = (!visible);
			_AddressControl2.Visible = (!visible);
			ddlBillTo.Visible = (!visible);
			lblBillTo.Visible = (!visible);
			_AddressControl1.IsEnabled = (!visible);
			//ddlShipTo.Enabled = (!visible);
//			btnAddEditAddress.Visible = (!visible);
		}

		private void btnEdit_Click(object sender, System.EventArgs e)
		{
			if(ddlShipTo.Enabled)
			{
				btnEdit.Text = "Cancel";
				btnSave.Text = "Update";
			}
			else
			{
				btnEdit.Text = "Edit";
				btnSave.Text = "Save";
				SetAddressInformation();
			}

			ddlShipTo.Enabled = (!ddlShipTo.Enabled);
			btnSave.Visible = (!ddlShipTo.Enabled);
			btnNew.Visible = ddlShipTo.Enabled;
			_AddressControl1.IsEnabled = (!ddlShipTo.Enabled);
		}

		private void btnNew_Click(object sender, System.EventArgs e)
		{
			if(ddlShipTo.Enabled)
			{
				btnNew.Text = "Cancel";
				btnSave.Text = "Save";
				_AddressControl1.ClearAll();
			}
			else
			{
				btnNew.Text = "New";
				btnSave.Text = "Update";
				SetAddressInformation();
			}

			ddlShipTo.Enabled = (!ddlShipTo.Enabled);
			btnSave.Visible = (!ddlShipTo.Enabled);
			btnEdit.Visible = ddlShipTo.Enabled;
			btnNew.Visible = ddlShipTo.Enabled;
			_AddressControl1.IsEnabled = (!ddlShipTo.Enabled);
		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			CustomersDB cust = new CustomersDB();
			if(btnEdit.Visible)
			{
				cust.UpdateCustomerAddress(
					Convert.ToInt32(ddlShipTo.SelectedValue),
					_AddressControl1.Address1,
					_AddressControl1.Address2,
					_AddressControl1.Attn,
					_AddressControl1.City,
					_AddressControl1.Region,
					_AddressControl1.Country,
					_AddressControl1.PostalCode,
					_AddressControl1.Phone1,
					_AddressControl1.Phone2,
					cust.CheckPrimaryAddress(Convert.ToInt32(Context.User.Identity.Name),Convert.ToInt32(ddlShipTo.SelectedValue)));
			}
			else
			{
				cust.AddCustomerAddress(
					Convert.ToInt32(Context.User.Identity.Name),
					_AddressControl1.Address1,
					_AddressControl1.Address2,
					_AddressControl1.Attn,
					_AddressControl1.City,
					_AddressControl1.Region,
					_AddressControl1.Country,
					_AddressControl1.PostalCode,
					_AddressControl1.Phone1,
					_AddressControl1.Phone2,
					false);
			}
			SetAddressInformation();
			ddlShipTo.Enabled = (!ddlShipTo.Enabled);
			btnSave.Visible = (!ddlShipTo.Enabled);
			btnNew.Visible = ddlShipTo.Enabled;
			btnEdit.Visible = ddlShipTo.Enabled;
			btnNew.Text = "New";
			btnEdit.Text = "Edit";
			_AddressControl1.IsEnabled = (!ddlShipTo.Enabled);
		}
	}
}
